<template>
  <a-modal :open="open" width="1300px" title="患者列表" :footer="false" centered @cancel="onCancel">
    <div class="h-[650px]">
      <a-form ref="formRef" :model="formState" class="form-style-flex">
        <a-form-item name="pyjm" class="w-[300px]">
          <a-input v-model:value="formState.pyjm" placeholder="姓名/助记码/卡号/手机号/身份证号" />
        </a-form-item>
        <a-form-item name="dateRange" label="日期范围" class="w-[340px]">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item class="ml-5">
          <a-checkbox v-model:checked="doctor" @change="onChangeChecked">本医生</a-checkbox>
        </a-form-item>
        <a-form-item label="就诊事项" class="w-[330px] ml-2">
          <a-select v-model:value="formState.dictOutpMatterIds" placeholder="请选择就诊事项" allow-clear mode="multiple" :max-tag-count="2">
            <a-select-option v-for="(item, index) in dictOutList" :key="index" :value="item.dictOutpMatterId">{{ item.matterName }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <div class="flex mb-2 justify-between">
        <div class="flex">
          <a-radio-group v-model:value="activeId" button-style="solid" @change="onChangeActive">
            <a-radio-button v-for="(item, index) in activeArray" :key="index" :value="item.key">{{ item.title }}({{ item.count }})</a-radio-button>
          </a-radio-group>
        </div>
        <div>
          <a-space wrap>
            <a-button @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="onClickSearch()">搜索</a-button>
          </a-space>
        </div>
      </div>
      <BaseTable
        :loading="loading"
        column-code="00001144"
        :data-source="tableData"
        bordered
        :height="480"
        :pagination="pagination"
        row-class-name="cursor-pointer"
        :custom-row="(record) => ({ onDblclick: () => onSelectRow(record) })"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'xh'">
            <div>{{ index + 1 }}</div>
          </template>
          <template v-if="column.dataIndex === 'ghzt'">
            <a-tag v-if="record.ghzt === 0" color="blue">候诊中</a-tag>
            <a-tag v-else-if="record.ghzt === 1" color="green">已就诊</a-tag>
            <a-tag v-else-if="record.ghzt === 2" color="red">已退号</a-tag>
            <a-tag v-else-if="record.ghzt === 4" color="red">待回诊</a-tag>
            <a-tag v-else color="green">已完诊</a-tag>
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" size="small" :disabled="record.ghzt !== 0 || !store.isCallConfig" @click="onCall(record)"> 呼叫 </a-button>
            <BaseButton confirm-text="确定允许退号?" type="text" danger size="small" :disabled="record.ghzt !== 1" @click="onHandleReturn(record)">
              允许退号
            </BaseButton>
          </template>
        </template>
      </BaseTable>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import useUserStore from '@/store/user'
import { post, get } from '@/utils/request'
import useStore from '../../store'

const { empId } = useUserStore()
const store = useStore()

const emit = defineEmits(['update:open', 'success', 'select'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const activeArray = ref([
  { key: '', title: '全部' },
  { key: 0, title: '候诊中' },
  { key: 3, title: '已完诊' },
  { key: 4, title: '待回诊' }
])

const doctor = ref(true)
const formRef = ref(null)
const activeId = ref('')
const dictOutList = ref([])
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  ghys: empId,
  type: 0,
  ksdm: [],
  ghzts: [0, 1, 3, 4]
})

// 获取就诊事项
const getDictOutList = async () => {
  const res = await post('/outp/mzdj/getDictOutpMatterNumberList')
  if (res.code !== 0) return message.error(res.msg)
  dictOutList.value = res.data
}

const onChangeActive = () => {
  if (activeId.value === 0) {
    formState.value.ghzts = [0, 1]
  } else if (activeId.value === '') {
    formState.value.ghzts = [0, 1, 3, 4]
  } else {
    formState.value.ghzts = [activeId.value]
  }
  // if (activeId.value === '') {
  //   formState.value.ghzts = [0, 1, 3, 4]
  // } else {
  //   formState.value.ghzts = [activeId.value]
  // }
  // formState.value.ghzts = activeId.value === 0 ? [0, 1, 3, 4] : activeId.value ? [activeId.value] : undefined
  getData()
}

const onChangeChecked = () => {
  if (!doctor.value) {
    delete formState.value.ghys
  } else {
    formState.value.ghys = doctor.value ? empId : ''
  }
}
const onClickSearch = () => {
  getRegistereCount()
  getData()
}
const { loading, tableData, pagination, getData } = useTable({
  url: '/outp/mzdj/getOutpRecordInfoList',
  params: formState.value
})
const onClickReset = () => {
  doctor.value = true
  // formState.value = {
  //   dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  //   ghys: empId,
  //   type: 0,
  //   ksdm: []
  // }
  formRef.value.resetFields()
  getData()
  activeId.value = ''
}
const getRegistereCount = async () => {
  const res = await post('/outp/outpComprehensive/getOutpRegistereCountList', {
    ...formState.value,
    ghzts: [],
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  if (res.code !== 0) return message.error(res.msg)
  activeArray.value[0].count = res.data.qb
  activeArray.value[1].count = res.data.hz
  activeArray.value[2].count = res.data.ywz
  activeArray.value[3].count = res.data.dhz
}

const getEmpInfo = async () => {
  const res = await get('/common/emp/getEmpInfo?empid=' + empId)
  if (res.code !== 0) return message.error(res.msg)
  formState.value.ksdm.push(res.data.ksdm)
  getData()
}

const onCancel = () => {
  emit('update:open', false)
}

const onSelectRow = (row) => {
  emit('select', row)
  emit('update:open', false)
}
const onHandleReturn = async (row) => {
  const { code, msg } = await post('/outp/mzys/modifyPatientClinicStatus', {
    ghzt: 0,
    jzbh: row.jzbh,
    ysbh: empId
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  getData()
}
const onCall = async (row) => {
  const res1 = await post(`/outp/doctorQueue/getDoctorQueueInfo`, { ghlbId: store.ghlbid })
  if (res1.code !== 0) message.error(res1.msg || '获取叫号队列失败')
  const res = await post('/outp/doctorQueue/doCallChosen', {
    QueueNo: row.queueNo,
    // QueueId: store.callConfigData.queueId
    QueueId: res1.data?.queueId
  })
  if (res.code !== 0) return message.error(res.msg)
  window.openExe?.callUpdSend(JSON.stringify(res.data)) //调用winform叫号
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      getEmpInfo()
      getRegistereCount()
      getDictOutList()
    } else {
      tableData.value = []
      onClickReset()
    }
  }
)
</script>

<style lang="less" scoped>
.button-active {
  line-height: 30px;
  border: 1px solid var(--primary-color);
}
.active {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
